﻿using dal.cgm_production_dao;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using utils;

namespace cover_label_printing
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.Timer validationTimer;

        public Form1()
        {
            InitializeComponent();
            // 初始化计时器
            validationTimer = new System.Windows.Forms.Timer();
            validationTimer.Interval = 500; // 延迟500毫秒
            validationTimer.Tick += new EventHandler(ValidationTimer_Tick);

            // 绑定事件
            productionDateTextBox.Enter += new EventHandler(productionDateTextBox_Enter);
            productionDateTextBox.Leave += new EventHandler(productionDateTextBox_Leave);
           

            expiryDateTextBox.Enter += new EventHandler(expiryDateTextBox_Enter);
            expiryDateTextBox.Leave += new EventHandler(expiryDateTextBox_Leave);

           

            batchTextBox.Enter += new EventHandler(batchTextBox_Enter);
            batchTextBox.Leave += new EventHandler(batchTextBox_Leave);

            assemblyDateTextBox.Enter += new EventHandler(assemblyDateTextBox_Enter);
            assemblyDateTextBox.Leave += new EventHandler(assemblyDateTextBox_Leave);

            // 设置初始的占位符文本和颜色
            SetPlaceholderText(productionDateTextBox, "yyyy-MM-dd");
            SetPlaceholderText(expiryDateTextBox, "yyyy-MM-dd");
            SetPlaceholderText(assemblyDateTextBox, "yyyy-MM-dd");
            SetPlaceholderText(batchTextBox, "XXXXXXXXXX");
            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();


        }


        #region 事件
        // 设置占位符文本和颜色
        private void SetPlaceholderText(TextBox textBox, string placeholderText)
        {
            textBox.Text = placeholderText;
            textBox.ForeColor = Color.Gray;
        }
        // 恢复正常文本颜色
        private void RemovePlaceholderText(TextBox textBox)
        {
            textBox.ForeColor = Color.Black;
        }
        // productionDateTextBox 进入事件
        private void productionDateTextBox_Enter(object sender, EventArgs e)
        {
            if (productionDateTextBox.Text == "yyyy-MM-dd")
            {
                productionDateTextBox.Text = "";
                RemovePlaceholderText(productionDateTextBox);
            }
        }
        // productionDateTextBox 离开事件
        private void productionDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(productionDateTextBox.Text))
            {
                SetPlaceholderText(productionDateTextBox, "yyyy-MM-dd");
            }
        }
        // expiryDateTextBox 进入事件
        private void expiryDateTextBox_Enter(object sender, EventArgs e)
        {
            if (expiryDateTextBox.Text == "yyyy-MM-dd")
            {
                expiryDateTextBox.Text = "";
                RemovePlaceholderText(expiryDateTextBox);
            }
        }
        // expiryDateTextBox 离开事件
        private void expiryDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(expiryDateTextBox.Text))
            {
                SetPlaceholderText(expiryDateTextBox, "yyyy-MM-dd");
            }
        }
        // batchTextBox 进入事件
        private void batchTextBox_Enter(object sender, EventArgs e)
        {
            if (batchTextBox.Text == "XXXXXXXXXX")
            {
                batchTextBox.Text = "";
                RemovePlaceholderText(batchTextBox);
            }
        }
        // batchTextBox 离开事件
        private void batchTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(batchTextBox.Text))
            {
                SetPlaceholderText(batchTextBox, "XXXXXXXXXX");
            }
        }

        // assemblyDateTextBox_Enter 进入事件
        private void assemblyDateTextBox_Enter(object sender, EventArgs e)
        {
            if (assemblyDateTextBox.Text == "yyyy-MM-dd")
            {
                assemblyDateTextBox.Text = "";
                RemovePlaceholderText(assemblyDateTextBox);
            }
        }
        // assemblyDateTextBox_Leave 离开事件
        private void assemblyDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(assemblyDateTextBox.Text))
            {
                SetPlaceholderText(assemblyDateTextBox, "yyyy-MM-dd");
            }
        }
        #endregion

        /// <summary>
        /// lockingButton_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lockingButton_Click(object sender, EventArgs e)
        {
            // 解析日期字段
            DateTime productionDate;
            DateTime expiryDate;
            DateTime assemblyDat;

            string batchDate = batchTextBox.Text; // 假设你有一个文本框用于输入批号

            // 检查输入格式是否正确 (yyyy-MM-dd)
            bool isProductionDateValid = DateTime.TryParseExact(productionDateTextBox.Text, "yyyy-MM-dd",
                                                                System.Globalization.CultureInfo.InvariantCulture,
                                                                System.Globalization.DateTimeStyles.None,
                                                                out productionDate);
            bool isExpiryDateValid = DateTime.TryParseExact(expiryDateTextBox.Text, "yyyy-MM-dd",
                                                            System.Globalization.CultureInfo.InvariantCulture,
                                                            System.Globalization.DateTimeStyles.None,
                                                            out expiryDate);

            // 使用正则表达式检查批号格式：XXXXXXXXXX
            bool isBatchDateValid = System.Text.RegularExpressions.Regex.IsMatch(batchDate, @"^\d{2}[A-Z]\d{7}$");

            //组装日期校验
            bool isAssemblyDateValid = DateTime.TryParseExact(assemblyDateTextBox.Text, "yyyy-MM-dd",
                                                          System.Globalization.CultureInfo.InvariantCulture,
                                                          System.Globalization.DateTimeStyles.None,
                                                          out assemblyDat);

            // 如果两个日期都有效
            if (isProductionDateValid && isExpiryDateValid && isAssemblyDateValid)
            {
                // 检查批号格式
                if (!isBatchDateValid)
                {
                    // 如果批号格式不正确，显示错误消息
                    MessageBox.Show("请输入正确的批号格式：10位例如24T3010231", "批号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return; // 结束方法，避免后续逻辑
                }

                // 如果当前处于“锁定时间”状态
                if (lockingButton.Text == "锁定参数")
                {
                    // 禁用文本框（锁定参数）
                    productionDateTextBox.Enabled = false;
                    expiryDateTextBox.Enabled = false;
                    batchTextBox.Enabled = false;
                    assemblyDateTextBox.Enabled = false;

                    // 将按钮文本改为“解锁参数”
                    lockingButton.Text = "解锁参数";
                }
                // 如果当前处于“解锁时间”状态
                else
                {
                    // 启用文本框（解锁参数）
                    productionDateTextBox.Enabled = true;
                    expiryDateTextBox.Enabled = true;
                    batchTextBox.Enabled = true;
                    assemblyDateTextBox.Enabled = true;

                    // 将按钮文本改回“锁定参数”
                    lockingButton.Text = "锁定参数";
                }
            }
            else
            {
                // 如果日期格式不正确，显示错误消息
                if (!isProductionDateValid || !isExpiryDateValid || !isAssemblyDateValid)
                {
                    MessageBox.Show("请输入正确的日期格式：yyyy-MM-dd", "日期格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// dmText_TextChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dmText_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时重置计时器
            validationTimer.Stop();
            validationTimer.Start();
        }

       

        private async void ValidationTimer_Tick(object sender, EventArgs e)
        {
            validationTimer.Stop(); // 停止计时器
            label2.Text = string.Empty;
            #region 参数校验
            if (lockingButton.Text == "锁定参数")
            {
                MessageBox.Show("请先锁定参数", "参数设置错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string dmCode = dmText.Text.Trim();

            if (!Regex.IsMatch(dmCode, "^[0-9A-Z]{12}$"))
            {
                dmText.BackColor = Color.LightCoral;
                HandleError("转运码格式校验失败");
            }

            AppendLog($"转运码: {dmCode} 格式校验成功", true);
            ApiLog.Debug($"转运码: {dmCode} 格式校验成功");
            dmText.BackColor = Color.LightGreen;

            DateTime date;
            string productionDate = "";
            string expiryDate = "";
            string assemblyDate = "";
            if (DateTime.TryParse(productionDateTextBox.Text.Trim(), out date))
            {
                productionDate = date.ToString("yyMMdd");
            }
            if (DateTime.TryParse(expiryDateTextBox.Text.Trim(), out date))
            {
                expiryDate = date.ToString("yyMMdd");
            }

            if (DateTime.TryParse(assemblyDateTextBox.Text.Trim(), out date))
            {
                assemblyDate = date.ToString("yyMMdd");
            }

            #endregion

            #region
            var client = new HttpClientHelper(ConfigurationManager.AppSettings["ServerUrl"]);

            // 示例：发送JSON请求
            var jsonRequest = new
            {
                production_batch = batchTextBox.Text.Trim(),
                mac_address = dmCode,
                production_date = productionDate,
                expiry_date = expiryDate,
                assembly_date = assemblyDate,
                sc = "30b9c3ca5e9911ef9aa806433e9aa661",
                sv = "80k9c3ca5e9911ef9aa806433e9aauy5"
            };

            try
            {
                string jsonResponse = await client.PostJsonAsync("/api/ApplicatorPrint", jsonRequest);

                var response = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                if (response.Code == 200)
                {
                    var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "applicator_label.frx");
                    FastReport.Report report = new FastReport.Report();
                    report.Load(reportPath);

                    var model = new
                    {
                        Mac = dmCode,
                        ProductionDate = productionDateTextBox.Text.Trim(),
                        ExpiryDate = expiryDateTextBox.Text.Trim(),
                        EightChars = dmCode.Length >= 6 ? dmCode.Substring(dmCode.Length - 6) : dmCode
                    };

                    //刷选可以打印字段特性的模型属性
                    var list = model.GetType().GetProperties();
                    //批量设置打印模板参数值
                    foreach (PropertyInfo pro in list)
                    {
                        var value = pro.GetValue(model, null);
                        //获取参数
                        FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                        if (param != null)
                        {

                            param.Value = value; //将属性的值赋值给名字相同的报表参数
                        }
                    }

                    report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                    report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                    report.Prepare();
                    if (checkViewPrint.Checked)
                    {
                        report.ShowPrepared();
                    }
                    else
                    {
                        // 直接打印报表
                        report.Print();

                    }

                    // 释放使用的资源
                    report.Dispose();

                    ResetDmText();
                    label2.Visible = true;
                    label2.ForeColor = Color.Green;
                    label2.Text = "打印成功";
                    #endregion
                }
                else
                {
                    HandleError(response.Message);
                }

            }
            catch (Exception ex)
            {
                HandleError(ex.Message);
            }
        }

        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="message"></param>
        private void HandleError(string message)
        {
            label2.Visible = true;
            label2.ForeColor = Color.Red;
            label2.Text = message;

            AppendLog($"转运码: {dmText.Text} {message}", false);
            ApiLog.Debug($"转运码: {dmText.Text} {message}");
            ResetDmText();

        }

        /// <summary>
        /// ResetDmText
        /// </summary>
        private void ResetDmText()
        {
            // 暂时禁用 TextChanged 事件处理程序
            dmText.TextChanged -= dmText_TextChanged;
            // 清空文本框并重置背景颜色
            dmText.Text = "";
            // 重新启用 TextChanged 事件处理程序
            dmText.TextChanged += dmText_TextChanged;

            // 聚焦到 dmText
            dmText.Focus();
        }

        /// <summary>
        /// AppendLog
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        private void AppendLog(string message, bool isError)
        {
            // 选择文本颜色
            Color textColor = isError ? Color.Black : Color.Red;

            // 设置光标位置并插入文本
            logRichTextBox.SelectionStart = logRichTextBox.TextLength;
            logRichTextBox.SelectionLength = 0; // 取消任何选择

            logRichTextBox.SelectionColor = textColor; // 设置颜色
            logRichTextBox.AppendText(message + "\n"); // 添加文本
            logRichTextBox.SelectionColor = logRichTextBox.ForeColor; // 恢复默认颜色
            logRichTextBox.ScrollToCaret(); // 自动滚动到最后
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogButton_Click(object sender, EventArgs e)
        {
            logRichTextBox.Clear();
        }
    }
}
